<template>
  <div class="page">
    <div class="title">
      <div v-on:click="_goBack" :style="{marginLeft: '10px'}">
        <img
          src="../assets/back.png"
          :style="{width: '30px', height: '30px'}"
        />
      </div>
      <div>{{ '/' + path.join("/") }}</div>
      <div v-on:click="_apiUpdate" :style="{marginRight: '10px'}">
        <img
          src="../assets/Update.png"
          :style="{width: '40px', height: '40px'}"
        />
      </div>
    </div>
    <div class="container">
      <div v-if="status === 'fold'">
        <Fold
          v-bind:path="path"
          v-on:enterFold="_enterFold"
        />
      </div>
      <div v-if="status === 'notebook'">
        <Notebook
          v-bind:path="path"
        />
      </div>
    </div>
  </div>
</template>

<script>
import Fold from './Fold'
import Notebook from './Notebook'
import { URL_UPDATE } from '@/config/index'

export default {
  name: 'Main',
  components: {
    Fold,
    Notebook
  },
  data () {
    return {
      path: [],
      status: 'fold'
    }
  },
  mounted () {
    window.history.pushState(null, null, document.URL)
    window.addEventListener('popstate', this._goBack, false)
  },
  destroyed () {
    window.removeEventListener('popstate', this._goBack, false)
  },
  methods: {
    _enterFold (fold, locked) {
      if (locked && !window.sessionStorage.getItem('password')) {
        var password = prompt('输入密码解锁', '')
        window.sessionStorage.setItem('password', password)
      }
      if (fold.slice(-2) === 'md') {
        this.status = 'notebook'
      }
      this.path.push(fold)
    },
    _goBack () {
      if (this.path.length === 0) {
        window.history.back()
      } else {
        window.history.pushState(null, null, document.URL)
        this.status = 'fold'
        this.path.pop()
      }
    },
    _apiUpdate () {
      fetch(URL_UPDATE, { method: 'GET' }).then(res => res.json()).catch(error => console.error('Error:', error)).then(res => {
        if (res.status === 'success') {
          console.log('update success!')
          this.path = []
        } else if (res.status === 'warn') {
          alert('未开启 git pull 功能!')
        } else {
          console.log(res)
          alert('error')
        }
      })
    }
  }
}
</script>

<style scoped>
.page {
  position: absolute;
  width: 100%;
  height: 100%;
}
.title {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 50px;
  z-index: 9999;
  background-color: white;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.container {
  position: absolute;
  top: 50px;
  width: 100%;
}
</style>
